#include "pm/task.h"

using namespace pm;

const wxString Task::TABLE_NAME   = wxT("tasks");


Task::Task()
: db::Object()
, m_unitCost(0)
, m_quantity(0)
, m_idProject(db::Object::undefined)
, m_idTag(db::Object::undefined)
{
}

Task::Task(wxSQLite3ResultSet& res)
: db::Object(res)
, m_name     (res.GetString(wxT("name")))
, m_unitCost (res.GetDouble(wxT("unit_cost")))
, m_quantity (res.GetDouble(wxT("quantity")))
, m_endDate(  res.GetDate(  wxT("end_date")))
, m_idProject(res.GetInt   (wxT("id_project")))
, m_idTag    (res.GetInt   (wxT("id_tag"), db::Object::undefined))
{
}

db::update_value_type Task::prepare_insert(wxSQLite3Database& db)
{
	if (m_idProject == db::Object::undefined) {
		return db::update_value_type(false, wxSQLite3Statement());
	}
	
	wxSQLite3Statement stmt = db.PrepareStatement("insert into tasks values(null, ?, ?, ?, ?, ?, ?)");
	stmt.Bind(1, m_name);
	stmt.Bind(2, m_unitCost);
	stmt.Bind(3, m_quantity);
	stmt.BindDate(4, m_endDate);
	stmt.Bind(5, m_idProject);
	if (m_idTag == db::Object::undefined) {
		stmt.BindNull(6);
	} else {
		stmt.Bind(6, m_idTag);
	}
	return db::update_value_type(true, stmt);
}

db::update_value_type Task::prepare_update(wxSQLite3Database& db)
{
	if (m_idProject == db::Object::undefined) {
		return db::update_value_type(false, wxSQLite3Statement());
	}
	
	wxSQLite3Statement stmt = db.PrepareStatement("update tasks set name = ?, unit_cost = ?, quantity = ?, end_date = ?, id_project = ?, id_tag = ? where id = ?");
	stmt.Bind(1, m_name);
	stmt.Bind(2, m_unitCost);
	stmt.Bind(3, m_quantity);
	stmt.BindDate(4, m_endDate);
	stmt.Bind(5, m_idProject);
	stmt.Bind(6, m_idTag);
	stmt.Bind(7, id());
	return db::update_value_type(true, stmt);
}



GetTasksByProject::GetTasksByProject(db::ID id_project)
: m_idProject(id_project)
{
}

wxSQLite3Statement GetTasksByProject::prepare(wxSQLite3Database& db)
{
	wxSQLite3Statement stmt = db.PrepareStatement("select id, name, unit_cost, quantity, end_date, id_project, id_tag from tasks where id_project = ? order by end_date asc");
	stmt.Bind(1, m_idProject);
	return stmt;
}


GetTasksTodoByProject::GetTasksTodoByProject(db::ID id)
: GetTasksByProject(id)
{
}

wxSQLite3Statement GetTasksTodoByProject::prepare(wxSQLite3Database& db)
{
	wxSQLite3Statement stmt = db.PrepareStatement("select id, name, unit_cost, quantity, end_date, id_project, id_tag from tasks where id_project = ? and quantity != 0 order by end_date asc");
	stmt.Bind(1, m_idProject);
	return stmt;
}


GetTasksDoneByProject::GetTasksDoneByProject(db::ID id)
: GetTasksByProject(id)
{
}

wxSQLite3Statement GetTasksDoneByProject::prepare(wxSQLite3Database& db)
{
	wxSQLite3Statement stmt = db.PrepareStatement("select id, name, unit_cost, quantity, end_date, id_project, id_tag from tasks where id_project = ? and quantity == 0 order by end_date asc");
	stmt.Bind(1, m_idProject);
	return stmt;
}
